package com.lib.audioDecoder;

import android.util.Log;

import com.lib.audioDecoder.player.AUDIO_CODEC_TYPE;

/**
 * Created by John on 2016/3/18.
 */
public class AudioCodec {

    static {
        System.loadLibrary("avcodec");
        System.loadLibrary("avfilter");
        System.loadLibrary("avformat");
        System.loadLibrary("avutil");
        System.loadLibrary("swresample");
        System.loadLibrary("swscale");
        System.loadLibrary("audio-decoder");
    }

    private final int mType;
    private static final int CODEC_TYPE_AAC = 0x15002;
    private static final int CODEC_TYPE_726 = 0x1100B;
    private static final int CODEC_TYPE_726LE = 0x11804;


    public AudioCodec(AUDIO_CODEC_TYPE audioType){
        switch (audioType){
            case AUDIO_CODEC_TYPE_AAC:
                mType = CODEC_TYPE_AAC;
                break;
            case AUDIO_CODEC_TYPE_726:
                mType = CODEC_TYPE_726;
                break;
            case AUDIO_CODEC_TYPE_726LE:
                mType = CODEC_TYPE_726LE;
                break;
            default:
                mType = -1;
        }
    }

    private long mCodecId = -1;
    private IDecodeCallback mDecodeCallback = null;

    public native String stringFromJNI();

    public boolean create(int sample_rate,
                       int channels, int sample_bit,
                       IDecodeCallback callback){
        this.mDecodeCallback = callback;

        mCodecId = this.create(mType, sample_rate, channels,
                sample_bit);

        if (mCodecId == 0){
            Log.e(AudioConst.TAG,"init decoder fail!");
            mCodecId = -1;
            return false;
        }

        return true;
    }

    public int decode(byte[] buffer, int offset,
                              int length){

        if(mCodecId == -1){
            return -1;
        }

        return this.decode(mCodecId,buffer,offset,length);
    }

    public synchronized void close(){
        if (mCodecId != -1){
            this.close(mCodecId);
            this.mCodecId = -1;
        }
    }

    private native long create(int codec, int sample_rate,
                               int channels, int sample_bit);

    private native int decode(long handle, byte[] buffer, int offset,
                              int length);


    private native void close(long handle);

    /**
     * Jni解码音频帧后会回到调该方法,故而方法名及传参都不能改动
     * @param data
     */
    public final void onFrame(byte[] data){
        if (mDecodeCallback != null){
            mDecodeCallback.onFrame(data);
        }
    }

    public interface IDecodeCallback{
        public void onFrame(byte[] data);
    }


}
